import ccclass = cc._decorator.ccclass;
import LayerControl from "./LayerControl";
import WelcomeLayer from "./WelcomeLayer";
import GameEngine from "./GameEngine";
import FireKit from "./fire/FireKit";
import Config from "./Config";
import StartGameVO from "./vo/StartGameVO";
import HumanPlayer from "./HumanPlayer";
import OpenResultVO from "./vo/OpenResultVO";
import PlayerManager from "./PlayerManager";
import GameEvent from "./GameEvent";
import SitDownVO from "./vo/SitDownVO";
import ConfirmColorVO from "./vo/ConfirmColorVO";
import OperationNotifyVO from "./vo/OperationNotifyVO";
import MoveResultVO from "./vo/MoveResultVO";
import EndGameVO from "./vo/EndGameVO";
import OpenCardDTO from "./dto/OpenCardDTO";
import MoveCardDTO from "./dto/MoveCardDTO";


@ccclass
export default class GameLayer extends cc.Component {

    /**
     * 界面组件
     */
    private _view: fgui.GComponent;
    /**
     * 引擎
     */
    private _engine: GameEngine;
    /**
     * 当前牌面的牌
     */
    private cards: number[];
    /**
     * Chair -> ID
     */
    private chairIds: { [chair: number]: number } = {};
    /**
     * 自己的编号
     */
    private _meChair: number;
    /**
     * 自己的游戏ID
     */
    private _meId: number = 1001;
    /**
     * 颜色
     */
    private _meColor: number;
    /**
     * 锁定状态
     */
    private _locked: boolean = true;
    /**
     * 开始的位置
     */
    private fromIndex: number = GameEngine.INVALID_INDEX;

    private _iconMapping: { [key: number]: string; } = {
        0x00: "蓝鼠",
        0x01: "蓝猫",
        0x02: "蓝狗",
        0x03: "蓝狼",
        0x04: "蓝豹",
        0x05: "蓝虎",
        0x06: "蓝狮",
        0x07: "蓝象",
        0x10: "红鼠",
        0x11: "红猫",
        0x12: "红狗",
        0x13: "红狼",
        0x14: "红豹",
        0x15: "红虎",
        0x16: "红狮",
        0x17: "红象"
    };

    /**
     * 颜色文本
     */
    private _colorText: fgui.GTextField;

    protected onLoad(): void {
        console.log("GameLayer onLoad");
        this._iconMapping[GameEngine.DARK_CARD] = "问号";
        this._iconMapping[GameEngine.NONE_CARD] = "透明";
        this.initFire();   //初始化事件绑定
        fgui.UIPackage.loadPackage("UI/Animal", () => { //加载资源包
            this._view = fgui.UIPackage.createObject("Animal", "GameLayer").asCom;
            this._colorText = this._view.getChild("ColorText").asTextField;
            this._view.makeFullScreen();
            fgui.GRoot.inst.addChild(this._view);
            this._view.getChild("CloseBtn").asButton.onClick(() => { //关闭按钮绑定事件
                LayerControl.inst().selectLayer(WelcomeLayer);
            }, this);
            this._engine = new GameEngine();
            this._engine.enter(PlayerManager.inst().create(new HumanPlayer(this._meId, "芳哥")));// 进入游戏
        });
    }


    /**
     * 初始化事件绑定
     */
    private initFire() {
        FireKit.use(Config.HUMAN_FIRE).onGroup(GameEvent.SIT_DOWN, this.sitDownLogic, this);
        FireKit.use(Config.HUMAN_FIRE).onGroup(GameEvent.START_GAME, this.startGameLogic, this);
        FireKit.use(Config.HUMAN_FIRE).onGroup(GameEvent.OPEN_RESULT, this.openResultLogic, this);
        FireKit.use(Config.HUMAN_FIRE).onGroup(GameEvent.CONFIRM_COLOR, this.confirmColorLogic, this);
        FireKit.use(Config.HUMAN_FIRE).onGroup(GameEvent.OPERATION_NOTIFY, this.operationNotifyLogic, this);
        FireKit.use(Config.HUMAN_FIRE).onGroup(GameEvent.MOVE_RESULT, this.moveResultLogic, this);
        FireKit.use(Config.HUMAN_FIRE).onGroup(GameEvent.END_GAME, this.endGameLogic, this);
    }

    /**
     *
     * @param sitDownVO
     */
    sitDownLogic = (sitDownVO: SitDownVO) => {
        this.chairIds[sitDownVO.chair] = sitDownVO.userId;
        if (sitDownVO.userId == this._meId) {   //如果是自己
            this._meChair = sitDownVO.chair;
        }
    };

    /**
     *
     * @param startGameVO
     */
    startGameLogic = (startGameVO: StartGameVO) => {
        this.cards = startGameVO.cards;
        this._locked = startGameVO.chair != this._meChair;
        this.cards.forEach((v, i) => {
            let row = Math.floor(i / 4);
            let col = i % 4;
            let cardCom = fgui.UIPackage.createObject("Animal", "CardComponent").asCom;
            cardCom.data = i; //位置
            cardCom.name = "card_" + i;
            this._view.addChild(cardCom);
            this.updateStyle(i);
            cardCom.x = 32 + (col * 180);
            cardCom.y = 320 + (row * 185);
            cardCom.onClick(() => {   //单击
                if (!this._locked) {    //没被锁定才允许操作
                    // 判断花色
                    let index = <number>cardCom.data;
                    let card = this.cards[index];
                    let color = card >> 4;
                    if (color === GameEngine.DARK) {
                        this._engine.open(new OpenCardDTO(this._meChair, index));
                    } else {
                        if (this.fromIndex == GameEngine.INVALID_INDEX) {
                            if (color == this._meColor) {           // 选择自己的牌
                                this.updateAndSelectStyle(index);   // 选中状态
                                this.fromIndex = index;
                            }
                        } else {
                            if (this._engine.canMove(this.fromIndex, index, this.cards)) {
                                this._engine.move(new MoveCardDTO(this._meChair, this.fromIndex, index));
                                this.fromIndex = GameEngine.INVALID_INDEX;
                                this.clearSelectStyle();    // 清除选中状态
                            } else {    //开始选中了，再切换别的牌
                                if (color == this._meColor) {           // 选择自己的牌
                                    this.updateAndSelectStyle(index);   // 选中状态
                                    this.fromIndex = index;
                                }
                            }
                        }
                    }
                }
            }, this);

        }, this);
    };

    /**
     *
     * @param openResultVO
     */
    openResultLogic = (openResultVO: OpenResultVO) => {
        this.cards[openResultVO.index] = openResultVO.card;
        this.clearSelectStyle();
        this.updateStyle(openResultVO.index);
        this.updateAndSelectStyle(openResultVO.index);
        this.fromIndex = GameEngine.INVALID_INDEX;
    };

    /**
     *
     * @param confirmColorVO
     */
    confirmColorLogic = (confirmColorVO: ConfirmColorVO) => {
        if (confirmColorVO.chair == this._meChair) {
            this._meColor = confirmColorVO.color;
            this._colorText.setVar("color", this._meColor == GameEngine.RED ? "红色" : "蓝色").flushVars();
        }
    };

    /**
     *
     * @param operationNotifyVO
     */
    operationNotifyLogic = (operationNotifyVO: OperationNotifyVO) => {
        this._locked = operationNotifyVO.chair != this._meChair;
    };

    /**
     *
     * @param moveResultVO
     */
    moveResultLogic = (moveResultVO: MoveResultVO) => {
        this.cards[moveResultVO.fromIndex] = moveResultVO.fromCard;
        this.cards[moveResultVO.toIndex] = moveResultVO.toCard;
        this.updateStyle(moveResultVO.fromIndex);
        this.updateStyle(moveResultVO.toIndex);
        if (this.cards[moveResultVO.toIndex] != GameEngine.NONE_CARD) {
            this.updateAndSelectStyle(moveResultVO.toIndex);
        }
        this.fromIndex = GameEngine.INVALID_INDEX;
    };

    /**
     * 游戏结束
     * @param endGameVO
     */
    endGameLogic = (endGameVO: EndGameVO) => {

    };

    /**
     * 更新牌的样式
     * @param index
     */
    private updateStyle(index: number): fgui.GComponent {
        let gObject = this._view.getChild("card_" + index).asCom;
        let v = this.cards[index];
        gObject.getChild("icon").asLoader.url = fgui.UIPackage.getItemURL("Animal", this._iconMapping[v]);
        gObject.getChild("active").asImage.visible = false;
        return gObject;
    }

    /**
     * 增加选择状态
     * @param index
     */
    private updateAndSelectStyle(index: number) {
        this.clearSelectStyle();            // 先清除选中
        this.updateStyle(index).getChild("active").asImage.visible = true;
    }

    /**
     * 清除选中状态
     */
    private clearSelectStyle() {
        for (let i = 0; i < GameEngine.MAX_CARD; i++) {
            let gObject = this._view.getChild("card_" + i);
            if (gObject != null) {
                gObject.asCom.getChild("active").asImage.visible = false;
            }
        }
    }

    /**
     * 释放资源回调
     */
    protected onDestroy(): void {
        console.log("GameLayer onDestroy");
        FireKit.use(Config.HUMAN_FIRE).offGroup(this);
        this._view.dispose();
    }


}
